﻿using AngleSharp;
using AngleSharp.Html.Dom;
using Microsoft.Extensions.DependencyInjection;

var config = Configuration.Default.WithDefaultLoader();
var html = await BrowsingContext.New(config).OpenAsync("https://www.qq.com/");
var img = html.QuerySelector("a.article-cell-bigimg img.img-cover") as IHtmlImageElement;

if (img != null)
{
    var result = DownloadFile(img.Source!);
    if (result.Result)
        Console.WriteLine("文件下载完成.");
}
else
    Console.WriteLine("文件下载失败.");

Console.ReadKey();

async Task<bool> DownloadFile(string fileUrl)
{
    // 采用 httpclient 工厂模式
    var serviceProvider = new ServiceCollection()
    .AddHttpClient()
    .BuildServiceProvider();
    var _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

    try
    {
        var http = _httpClientFactory?.CreateClient();
        if (http is not null)
        {
            var response = await http.GetAsync(fileUrl);

            if (!Directory.Exists("download"))
            {
                Directory.CreateDirectory("download");
            }

            var uri = new Uri(fileUrl);
            var filename = Path.Combine("download", Path.GetFileName(uri.LocalPath));
            using var file = File.Create(filename);
            await response.Content.CopyToAsync(file);
            return true;
        }

        return false;

    }
    catch (Exception)
    {
        return false;
    }

}
